package bbstorespringmvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import bbstorespringmvc.model.Book;
import bbstorespringmvc.repository.BookRepository;

@Controller
public class BookEditController {
	@Autowired
	BookRepository bookRepository;

	@RequestMapping("/updatebook")
	public ModelAndView bookEditSubmit(@RequestParam("id") Long id,
			@RequestParam("isbn") String isbn,
			@RequestParam("title") String title,
			@RequestParam("price") int price) {
		// check isbn

		Book bookToUpdate = (Book) bookRepository.findById(id);
		if (bookToUpdate == null)
			return new ModelAndView("error", "id", id);
		bookToUpdate.setIsbn(isbn);
		bookToUpdate.setTitle(title);
		bookToUpdate.setPrice(price);

		bookRepository.merge(bookToUpdate);

		return new ModelAndView("redirect:/displaydetails?id="
				+ bookToUpdate.getId()); // no error => redirect to book display
	}

	@RequestMapping("/getbooktoedit")
	public ModelAndView bookGetEdit(@RequestParam("id") Long id) {

		Book bookToUpdate = (Book) bookRepository.findById(id);
		if (bookToUpdate == null)
			return new ModelAndView("error", "id", id);

		ModelAndView mv = new ModelAndView("formbookedit", "booktoupdate",
				bookToUpdate);
		return mv;
	}
}
